<?php

/**
 * Log.php
 *
 * Holds class Log
 *
 * @package Library
 */

/**
 * Log
 *
 * Logs events
 *
 * @package Library
 */
class Log {

	/**
	 * New events
	 * @var array $_event
	 */
	protected $_event = array();

	/**
	 * Log file
	 * @var string $_file
	 */
	protected $_file;

	/**
	 * Request resource
	 * @var Mvc_Request $_request
	 */
	protected $_request;

	/**
	 * Constructor
	 *
	 * @param Mvc_Request $request
	 * @param string $file (should not be a relative path)
	 * @return void
	 */
	public function __construct(Mvc_Request $request, $file) {
		$this->_file    = $file;
		$this->_request = $request;
	}

	/**
	 * Destructor
	 *
	 * @return void
	 */
	public function __destruct() {
		try {
			$this->shutdown();
		}
		catch(Exception $e) {
			//Exceptions can't be thrown in destructors before PHP5.3.0;
			//http://php.net/ChangeLog-5.php
		}
	}

	/**
	 * Writes event
	 *
	 * @param string $message (optional)
	 * @param string $file (optional)
	 * @param integer $line (optional)
	 * @return Log (fluent interface)
	 */
	public function write($message = '', $file = null, $line = null) {
		$event = '[' . date('Y-m-d H:i:s') . '] (' . $this->_request->getServer('REMOTE_ADDR') . ' @ ' . $this->_request->getServer('REQUEST_URI') . ')';
		if('' != $message) {
			$event .= ' ' . $message;
		}
		if(isset($file)) {
			$event .= ' [' . $file;
			if(isset($line)) {
				$event .= ':' . $line;
			}
			$event .= ']';
		}

		$this->_event[] = $event . PHP_EOL;

		return $this;
	}

	/**
	 * Shuts down log
	 *
	 * @throws Exception
	 * @return void
	 */
	public function shutdown() {
		if(!empty($this->_event)) {
			// File will be created if non existant
			$handle = file_put_contents($this->_file, implode(PHP_EOL, $this->_event), FILE_APPEND | LOCK_EX);
			if(false === $handle) {
				throw new Exception('Cannot write log to file');
			}
		}
	}

}
